//
//  MHFMDB+Update.m
//  数据库的读写封装
//
//  Created by zsgjs on 2017/2/21.
//  Copyright © 2017年 zsgjs. All rights reserved.
//

#import "MHFMDB+Update.h"

@implementation MHFMDB (Update)

#pragma mark - 更新数据操作
/**
 *  更新记录到数据库
 */
- (bool)updateSQL
{
    __block NSMutableString *setstring = [NSMutableString string];
    [self.data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        setstring = [NSMutableString stringWithFormat:@"%@%@",setstring,[NSString stringWithFormat:@"`%@`='%@' , ",key,obj]];
    }];
    NSString * tmp  = [setstring stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" , "]];
    NSString *sql = [NSString stringWithFormat:@"UPDATE `%@` set %@ %@",self.currentTableName,tmp,self.where];
    return [self excuteUpdateWithSql:sql];
}

/**
 *  从字典更新记录到数据库
 */
- (bool)updateWithData:(id)data
{
    if ([data isKindOfClass:[NSData class]]) {
        //从json导入数据
        [self datawithJson:data];
    }
    if ([data isKindOfClass:[NSDictionary class]] || [data isKindOfClass:[NSMutableDictionary class]]) {
        //从字典导入数据
        [self dataWithDict:data];
    }
    if ([data isKindOfClass:[NSArray class]] || [data isKindOfClass:[NSMutableArray class]]) {
        //从数组导入数据则遍历批量更新
        __block BOOL allsave=YES;
        [data enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            if ([obj isKindOfClass:[NSDictionary class]]) {
                [self dataWithDict:obj];
                if (![self updateSQL]) {
                    allsave = NO;
                    //打印到控制台错误信息
                    NSLog(@"PYFMDB UPDATE FAILED:%@",self.lastSql);
                }
            }
        }];
        return allsave;
    }
    return [self updateSQL];
}

/**
 *  更新指定字段值
 */
- (bool)updateValue:(id)value forField:(NSString *)field
{
    self.data = [self filterWithDict:[NSDictionary dictionaryWithObject:value forKey:field]];
    return  [self updateSQL];
}

@end
